package fragmentson;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wq.cycling.DemoApplication;
import com.wq.cycling.R;

import java.util.ArrayList;

import activity.SonActivity;
import bean.EntityForSimple;
import bean.MessageForSimple;
import bean.MessageForSos;
import fragmentson.backhandle.BackHandledFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.ApiUtil;
import util.Constant;
import util.adapter.MessageAdapter;
import util.dialog.DialogFromMiddle;
import util.myview.springview.DefaultFooter;
import util.myview.springview.DefaultHeader;
import util.myview.springview.SpringView;


/**
 * 报警列表
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class MessageList extends BackHandledFragment {

	private View rootView;
	private ListView listView;
	private MessageAdapter adapter;
	private SpringView springView;
	private int page = 1;
	private int count = 30;
	private ArrayList<EntityForSimple> mDatas = new ArrayList<>();
	private boolean isLoadAll = false;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_messagelist, null);
		initView();
		initData(page);
		return rootView;
	}

	public void initData(final int p){
		ApiUtil.getApiService().getAllAlarmsForDevice(DemoApplication.getToken(),DemoApplication.getDeviceid(),p+"",count+"").enqueue(new Callback<MessageForSos>() {
			@Override
			public void onResponse(Call<MessageForSos> call, Response<MessageForSos> response) {
				try {
					if(page==1){
						springView.onFinishFreshAndLoad();
						mDatas.clear();
					}else{
						springView.onFinishFreshAndLoad();
					}
					page++;
					MessageForSos entity = response.body();
					if(entity.getCode().equals("10008")){
						if(entity.getData().getAlarms().size()!=count) {
							isLoadAll = true;
						}
						mDatas.addAll(entity.getData().getAlarms());
						adapter.notifyDataSetChanged();
					}else{
						Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			@Override
			public void onFailure(Call<MessageForSos> call, Throwable t) {
				Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
			}
		});
	}

	private void initView() {
		// TODO Auto-generated method stub
		((TextView) rootView.findViewById(R.id.tv_title)).setText(R.string.main_tab3);

		listView = ((ListView) rootView.findViewById(R.id.lv_sos));
		adapter = new MessageAdapter(getActivity(),mDatas);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					Intent intent = new Intent(getActivity(), SonActivity.class);
					Bundle bundle = new Bundle();
					bundle.putInt("code", Constant.MessageParticulars);
					bundle.putString("lat", mDatas.get(position).getLat());
					bundle.putString("lng", mDatas.get(position).getLng());
					bundle.putString("name", mDatas.get(position).getDevicename());
					bundle.putString("content", mDatas.get(position).getAlarmType());
					bundle.putString("time", mDatas.get(position).getAlarmTime());
					intent.putExtras(bundle);
					startActivity(intent);
			}
		});
		initSpringView();
		rootView.findViewById(R.id.tv_clear).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogFromMiddle dialogFormMiddle = new DialogFromMiddle(getActivity());
				dialogFormMiddle.setSureListener(new DialogFromMiddle.Sure() {
					@Override
					public void onSure() {
						// TODO Auto-generated method stub
						String alramids = "";
						for(int i=0;i<mDatas.size();i++){
								alramids = alramids + mDatas.get(i).getAlarmid() + ",";
						}
						if(!alramids.isEmpty()) {
							alramids = alramids.substring(0,alramids.length()-1);
						}

						ApiUtil.getApiService().deleteAlarms(DemoApplication.getToken(),alramids).enqueue(new Callback<MessageForSimple>() {
							@Override
							public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
								try {
									MessageForSimple entity = response.body();
									if(entity.getCode().equals("10008")){
										mDatas.clear();
										page = 1;
										initData(page);
									}else{
										Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
									}

								} catch (Exception e) {
									e.printStackTrace();
								}
							}
							@Override
							public void onFailure(Call<MessageForSimple> call, Throwable t) {
								Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
							}
						});
					}
				});
				dialogFormMiddle.show(getResources().getString(R.string.dialog_title8), getResources().getString(R.string.dialog_content8), "", "", getResources().getString(R.string.dialog_yes8),getResources().getString(R.string.dialog_no8), true);
			}
		});

	}
	private void  initSpringView(){
		springView = (SpringView) rootView.findViewById(R.id.springview);
		springView.setType(SpringView.Type.FOLLOW);
		springView.setListener(new SpringView.OnFreshListener() {
			@Override
			public void onRefresh() {
				/*new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						springView.onFinishFreshAndLoad();
					}
				}, 1000);*/
				isLoadAll = false;
				page = 1;
				initData(page);
			}

			@Override
			public void onLoadmore() {
				/*new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						springView.onFinishFreshAndLoad();
					}
				}, 1000);*/
				if(isLoadAll){
					springView.onFinishFreshAndLoad();
				}else {
					initData(page);
				}
			}
		});
		springView.setHeader(new DefaultHeader(getActivity()));
		springView.setFooter(new DefaultFooter(getActivity()));
	}

	public static MessageList newInstance() {
		MessageList fragment = new MessageList();
		return fragment;
	}

	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()){
				default:
					break;
			}
		}
	};

	@Override
	public boolean onBackPressed() {
		return false;
	}

}
